<?php
$errors = array();

if(!is_writable(APP.'config'))
{
	$error =	'Please make the directory <strong>config</strong> in the main application directory writable for PHP (chmod to 755) to continue with the installation of '.TITLE.'.<br/>
				You may reset the folder\'s permissions after completing the installation.';
	
	require FW.'management'.DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR.'error.html';
	
	exit();
}

if(isset($_POST['install']))
{
	# Database
	$adapter = $_POST['adapter'];
	$host = $_POST['host'];
	$user = $_POST['user'];
	$pass = $_POST['pass'];
	$database = $_POST['database'];
	$prefix = $_POST['prefix'];
	
	require FW.'db'.DIRECTORY_SEPARATOR.$adapter.'.php';
	
	if(empty($user)) $errors['user'] = 'Please enter a username.';
	if(empty($database)) $errors['database'] = 'Please enter the name of a database.';
	
	if(!empty($prefix))
	{
		if(!preg_match('/^(\w+)$/', $prefix))
		{
			$errors['prefix'] = 'Must be alphanumeric.';
		} else
		{
			$prefix .= '_';
		}
	}
	
	if(empty($host))
	{
		$errors['host'] = 'Please enter a host.';
	} elseif(!isset($errors['user']))
	{
		if(!db::connect($host, $user, $pass))
		{
			if(db::error_key() === 'invalid_host')
			{
				$errors['host'] = "Couldn't connect to host.";
			} else
			{
				$errors['user'] = 'Access to host denied.';
			}
		} elseif(!isset($errors['database']))
		{
			if(!db::select_db($database) && !(db::query('CREATE DATABASE '.$database, false) && db::select_db($database)))
			{
				$errors['database'] = "User isn't allowed to access this database.";
			}
		}
	}
	
	# Administrator
	$username = $_POST['username'];
	$password = $_POST['password'];
	$repeat = $_POST['repeat'];
	
	if(strlen($username) < 3 || strlen($username) > 12) $errors['username'] = 'Must be between 3 and 12 letters long.';
	if(strlen($password) < 6) $errors['password'] = 'Must be at least 6 letters long.';
	if($repeat != $password) $errors['repeat'] = "Doesn't match the previously entered password.";
	
	# Install
	if(!$errors)
	{
		# Configuration
		if(db::query('CREATE TABLE `'.$prefix.'config` (
			`key` VARCHAR(12),
			`value` VARCHAR(255) COLLATE utf8_bin,
			PRIMARY KEY (`key`),
			UNIQUE (`key`)
		)', false))
		{
			$query = 'INSERT INTO `'.$prefix.'config` VALUES
				("title", "'.db::escape(TITLE).'"),
				("version", '.VERSION.'),
				("lang", "eng"),
				("style", "default")';
			
			foreach($config as $key=>$value)
			{
				$query .= ', ("'.$key.'", "'.db::escape($value).'")';
			}
			
			db::query($query, false);
		}
		
		# Models
		define('DB_PREFIX', $prefix);
		
		$directory = opendir(APP.'model');
		while($file = readdir($directory))
		{
			if($file === '.' || $file === '..') continue;
			
			require APP.'model'.DIRECTORY_SEPARATOR.$file;
			
			$class = substr($file, 0, -4);
			$model = call_user_func(array($class, 'install'));
			
			$query = 'CREATE TABLE `'.$prefix.$class.'` (`id` INT(10) UNSIGNED AUTO_INCREMENT';
			
			foreach($model as $key=>$value)
			{
				if(is_array($value))
				{
					$query .= ', `'.$key.'` INT(10) UNSIGNED';
					
					$subquery = 'CREATE TABLE `'.$prefix.$class.'_'.$key.'` (`id` INT(10) UNSIGNED AUTO_INCREMENT';
					
					foreach($value as $subkey=>$subvalue)
					{
						$subquery .= ', `'.$subkey.'` '.$subvalue;
					}
					
					$subquery .= ', PRIMARY KEY (`id`))';
					
					db::query($subquery, false);
				} else
				{
					$query .= ',`'.$key.'` '.$value;
				}
			}
			
			$query .= ', PRIMARY KEY (`id`)) CHARACTER SET utf8';
			
			db::query($query, false);
		}
		
		# Administrator
		db::query('INSERT INTO `'.$prefix.'User` (`admin`, `username`, `password`, `status`) VALUES (1, "'.db::escape($username).'", "'.md5($password).'", 1)', false);
		
		# Version control
		require APP.'config'.DIRECTORY_SEPARATOR.'version.php';
		
		if(is_callable(array('version', 'install')))
		{
			version::install($prefix);
		}
		
		# Configuration file
		file_put_contents(APP.'config'.DIRECTORY_SEPARATOR.'db.php', "<?php\ndefine('DB_ADAPTER', '$adapter');\ndefine('DB_HOST', '$host');\ndefine('DB_USER', '$user');\ndefine('DB_PASS', '$pass');\ndefine('DB_NAME', '$database');\ndefine('DB_PREFIX', '$prefix');");
		
		header('Location: '.WEB);
		
		exit();
	}
}

require FW.'management'.DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR.'install.html';

exit();